package com.unisedu.oa.Interceptor;

import com.unisedu.oa.utils.JsonUtils;
import com.unisedu.oa.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SecurityInterceptor implements HandlerInterceptor {

    @Value("${config.secret}")
    private String secret;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
        final String authHeader = req.getHeader("authorization");
        if ("OPTIONS".equals(req.getMethod())) {
            res.setStatus(HttpServletResponse.SC_OK);
            return false;
        } else{
            if (authHeader == null || !authHeader.startsWith("Bearer;")) {
                JsonUtils.formatResult(res,403,"UserToken is not found!");
                return false;
            }
            final String token = authHeader.substring(7);
            String employeeId = JwtUtils.validateToken(token,secret);
            if(employeeId != null){
                req.setAttribute("employeeId",employeeId);
                return true;
            }else{
                JsonUtils.formatResult(res,403,"UserToken is not available!");
                return false;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
